package com.zwg.git_customview.viewpager2.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.zwg.git_customview.R

class IndicatorView : View {

    private var selectedIndex: Int = 0
    private var indicatorCount: Int = 0
    private val indicatorRadius: Float = 12f // 指示器半径
    private val indicatorSpacing: Float = 12f // 指示器之间的间距
    private val indicatorPaint: Paint = Paint()
    private val indicatorPaint2: Paint = Paint()

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    init {
//        indicatorPaint.color = Color.BLUE // 指示器颜色
        indicatorPaint.color = resources.getColor(R.color.color_0368d9_type)
        indicatorPaint.isAntiAlias = true // 抗锯齿

//        indicatorPaint2.color = Color.GRAY // 指示器颜色
        indicatorPaint2.color = resources.getColor(R.color.color_D9D9D9_757575)// 指示器颜色
        indicatorPaint2.isAntiAlias = true // 抗锯齿
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        if (indicatorCount <= 0 || canvas == null) return

        val totalWidth =
            (indicatorCount * indicatorRadius * 2) + ((indicatorCount - 1) * indicatorSpacing)
        val startX = (width - totalWidth) / 2
        val centerY = height / 2f

        for (i in 0 until indicatorCount) {
            val cx = startX + (i * (indicatorRadius * 2 + indicatorSpacing)) + indicatorRadius
            canvas.drawCircle(cx, centerY, indicatorRadius, indicatorPaint2)
        }

        // 绘制选中的指示器
        if (selectedIndex in 0 until indicatorCount) {
            val selectedCx =
                startX + (selectedIndex * (indicatorRadius * 2 + indicatorSpacing)) + indicatorRadius
            canvas.drawCircle(selectedCx, centerY, indicatorRadius * 1.5f, indicatorPaint)
        }
    }

    fun setSelectedIndex(index: Int) {
        selectedIndex = index
        invalidate()
    }

    fun setIndicatorCount(count: Int) {
        indicatorCount = count
        invalidate()
    }
}
